$(document).ready(function() {
	var domObj = {
		$nameTxt : $("#nameTxt"),
		$sendBtn : $("#sendBtn"),
		$messageTxt : $("#messageTxt"),
		$messages : $("#messages")
	};
	var webSocket = new WebSocket("ws:10.20.53.69:8080/com-byteslounge-websockets/websocket");

	webSocket.onerror = function(event) {
		controlFnc.onError(event)
	};

	webSocket.onopen = function(event) {
		controlFnc.onOpen(event)
	};

	webSocket.onmessage = function(event) {
		controlFnc.onMessage(event)
	};

	var baseFnc = {
		isMinStatus : function() {
			var isMin = false;
			if (window.outerWidth != undefined) {
				isMin = window.outerWidth <= 160 && window.outerHeight <= 30;
			} else {
				isMin = window.screenTop < -30000 && window.screenLeft < -30000;
			}
			return isMin;
		}

	}

	var controlFnc = {
		flushTitle : function() {

		},
		onOpen : function(event) {
			this.showMessage("连接服务器成功");
		},
		onMessage : function(event) {
			this.showMessage(event.data);
			doFlashTitle();
		},
		onError : function(event) {
			alert(event.data);
		},
		sendMessage : function() {
			var message = domObj.$messageTxt.val();
			var name = domObj.$nameTxt.val();
			if (!message) {
				this.showMessage("不能发送空消息");
				return false;
			}
			webSocket.send(name + " says : " + message)
			this.clearMessage();
			return false;
		},
		showMessage : function(message) {
			domObj.$messages.prepend('<div class="alert alert-success" role="alert">'+ message+'</div>');
		},
		clearMessage : function() {
			domObj.$messageTxt.val("");
		}

	}

	$("#sendBtn").click(function() {
		doFlashTitle();
			// controlFnc.sendMessage();
		})
	$("#messageTxt").keyup(function(event) {
				if (event.keyCode === 13) {
					controlFnc.sendMessage();
				}
			})

	var isWindowFocus = true;
	function focusin() {
		isWindowFocus = true;
	}
	function focusout() {
		isWindowFocus = false;
	}
	// 注册焦点变化监听器
	if ("onfocusin" in document) {// for IE
		document.onfocusin = focusin;
		document.onfocusout = focusout;
	} else {
		window.onblur = focusout;
		window.onfocus = focusin;
	}

	var flashStep = 0; // 交替变量
	var flashTitleRun = false; // 是否正在执行
	var normalTitle = "正常显示的标题";
	function flashTitle() {
		// 仅窗口不在焦点时闪烁title，回到焦点时停止闪烁并将title恢复正常
		if (isWindowFocus) {// 当前处于焦点
			document.title = normalTitle;
			flashTitleRun = false;
			return;// 退出循环
		}

		flashTitleRun = true;
		flashStep++;
		if (flashStep == 3) {
			flashStep = 1;
		}
		if (flashStep == 1) {
			document.title = "【您有新的消息】";
		}
		if (flashStep == 2) {
			document.title = "【　　　　　　】";
		}
		window.focus();
		setTimeout(function() {
					flashTitle();
				}, 500); // 循环
	}
	// 调用这个执行标题闪烁，而不是直接调用flashTitle，保证多次调用只会执行一次。
	function doFlashTitle() {
		if (!flashTitleRun)// 没有执行时，才执行
			flashTitle();
	}
});
